package com.atguigu.process.service.impl;

import com.atguigu.common.result.Result;
import com.atguigu.model.process.ProcessTemplate;
import com.atguigu.model.process.ProcessType;
import com.atguigu.process.mapper.ProcessTemplateMapper;
import com.atguigu.process.service.ProcessService;
import com.atguigu.process.service.ProcessTemplateService;
import com.atguigu.process.service.ProcessTypeService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ProcessTemplateServiceImpl extends ServiceImpl<ProcessTemplateMapper, ProcessTemplate>
        implements ProcessTemplateService {
    @Autowired
    private ProcessTypeService processTypeService;

    @Autowired
    private ProcessService processService;

    @Override
    public Result<IPage<ProcessTemplate>> selectPageProcessTemplate(Long page, Long limit) {
        IPage<ProcessTemplate> pageInfo = new Page<>(page, limit);
        page(pageInfo);
        List<ProcessTemplate> templates = pageInfo.getRecords();
        Set<Long> processTypeIds = templates.stream()
                .map(ProcessTemplate::getProcessTypeId).collect(Collectors.toSet());
        Map<Long, String> typeMap = processTypeService.listByIds(processTypeIds).stream()
                .collect(Collectors.toMap(ProcessType::getId, ProcessType::getName, (old, newKey) -> newKey));
        //如果要使用下面这种流的方式用peek对数据进行操作，那么就必须调用一个流的终止方法，否则只像下面这样调用peek，peek中的操作并不会执行，
        //所以templates中的元素也不会被赋值。因为流中，只有执行了终止方法后所有的操作才会执行，不执行终止方法，中间操作都不会执行。
//        templates.stream().peek(t->t.setProcessTypeName(typeMap.get(t.getProcessTypeId())));
        for(ProcessTemplate processTemplate : templates) {
            processTemplate.setProcessTypeName(typeMap.get(processTemplate.getProcessTypeId()));
        }
        return Result.ok(pageInfo);
    }

    @Override
    public void publish(Long id) {
        //发布审批模板
        ProcessTemplate template = getById(id);
        template.setStatus(1);
        updateById(template);
        //然后完成流程定义的部署
        String path = template.getProcessDefinitionPath();
        if(!StringUtils.isEmpty(path)){
            processService.deployByZip(path);
        }
    }
}
